package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.service.SpecParamService;
import com.leyou.item.service.SpuDetailService;
import com.leyou.item.service.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpuDetailServiceImpl extends ServiceImpl<SpuDetailMapper, SpuDetail> implements SpuDetailService {

    @Autowired
    private SpuService spuService;

    @Autowired
    private SpecParamService specParamService;

    @Override
    public SpuDetailDTO querySpuDetailById(Long spuId) {

        return new SpuDetailDTO(this.getById(spuId));
    }

    @Override
    public List<SpecParamDTO> querySpecsValues(Long spuId, Boolean searching) {

        // 1.查询tb_spu_detail表中的数据，并转换得到的键值对信息
//        SpuDetail spuDetail = this.query().eq("spu_id", spuId).one();
        SpuDetail spuDetail = this.getById(spuId);

        String specification = spuDetail.getSpecification();

        // key ==> paramId,value,就是需要的value值 理论上可以无限嵌套map集合
        //JsonUtils.nativeRead(this.getById(spuId).getSpecification(), new TypeReference<Map<Long,Object>>() {});

        //Map<Long, Object> mapList = JsonUtils.nativeRead(specification, new TypeReference<Map<Long, Object>>() {});

        // 只能处理单层map
        Map<Long, Object> map = JsonUtils.toMap(specification, Long.class, Object.class);

        Spu spu = spuService.getById(spuId);

        List<SpecParamDTO> specParamDTOS = specParamService.querySpecParams(spu.getCid3(), null, searching);

//        specParamDTOS.stream().map(specParamDTO -> specParamDTO.setValue(map.get(map.get(specParamDTO.getId())));

//        specParamDTOS.forEach(specParamDTO -> specParamDTO.setValue(map.get(specParamDTO.getId())));

        for (SpecParamDTO specParamDTO : specParamDTOS) {

            specParamDTO.setValue(map.get(specParamDTO.getId()));

        }

        return specParamDTOS;
    }
}
